package com.yupi.yupao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.common.RedisMatchHistoryService;
import com.yupi.yupao.config.JWTConfig;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.dto.WxLoginDto;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.mapper.UserMapper;
import com.yupi.yupao.utils.AlgorithmUtils;

import com.yupi.yupao.utils.HttpClientUtils;
import javafx.util.Pair;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSON;
import static com.yupi.yupao.contant.UserConstant.ADMIN_ROLE;
import static com.yupi.yupao.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 *

 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private UserMapper userMapper;
    @Value("${AppID}")
    private String AppId;
    @Value("${AppSecret}")
    private String AppSecret;
    @Resource
    private JWTConfig jwtConfig;
    @Resource
            private RedisMatchHistoryService redisMatchHistoryService;


    //创建map存放用户信息
    Map<String,Object> map=new HashMap<>();



    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yupi";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @param planetCode    星球编号
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }


    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return 脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        safetyUser.setProfile(originUser.getProfile());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 内存查询版（先把所有数据查询出来，再通过gson工具处理）
     * @param tagNameList
     * @return
     */
    @Override
    public List<User> getUserByTagNameList(List<String> tagNameList) {
        //判空
        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return this.getUserByTagNameListBySql(tagNameList);


    }

    /**
     *
     * @param user 用户传递需要修改的user（这里改成dto会比较好）
     * @param loginUser 登录的用户（做鉴权用）
     * @return
     */
    @Override
    public Integer updateUser(User user,User loginUser) {
        Long userId = user.getId();
        if(userId<=0||userId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //如果不是管理员，只能修改自己
        if(!isAdmin(loginUser)&& userId==loginUser.getId()){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(user);

        if (oldUser==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);

    }

    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request==null){
            return null;
        }

        Object userInfo = request.getSession().getAttribute(USER_LOGIN_STATE);
        if(userInfo==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return (User) userInfo;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }
    @Override
    public boolean isAdmin(User loginuser) {

        return loginuser != null && loginuser.getUserRole() == ADMIN_ROLE;
    }


    /**
     * 推荐匹配用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {


        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("tags");
        queryWrapper.select("id", "tags");
        List<User> userList = this.list(queryWrapper); // 获取所有用户列表

        String tags = loginUser.getTags();
        if (tags == null||tags.length()<=0) {
            throw new BusinessException(ErrorCode.HEARD_ERROR);
        }

        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());

        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算当前用户和所有用户的相似度
        for (User user : userList) {
            String userTags = user.getTags();
            // 无标签的 或 当前用户为自己 或 已经匹配过
            if (StringUtils.isBlank(userTags) || user.getId().equals(loginUser.getId())) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算相似度分数
            // 遍历listStr1中的每个元素
            for (int i = 0; i < tagList.size(); i++) {
                String str1 = tagList.get(i);

                // 遍历listStr2中的每个元素
                for (int j = 0; j < userTagList.size(); j++) {
                    String str2 = userTagList.get(j);

                    // 计算str1和str2之间的编辑距离
                    long distance = AlgorithmUtils.minDistance(str1, str2);
                    if(distance<=0){
                        list.add(new Pair<>(user, distance));
                    }
                    log.info("相似度分数："+distance);

                    System.out.println("The edit distance between \"" + str1 + "\" and \"" + str2 + "\" is: " + distance);
                }
            }

//            long distance = AlgorithmUtils.minDistance(tagList, userTagList);

        }

        // 按编辑距离从小到大排序
//        List<Pair<User, Long>> topUserPairList = list.stream()
//                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
////                .limit(num)
//                .collect(Collectors.toList());
        List<Pair<User, Long>> topUserPairList=list.stream().filter(item->item.getValue()!=tagList.size()).collect(Collectors.toList());

        // 按照排序后提取相似度最高的用户ID
        List<Long> userListVo = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        if(userListVo.size()<=0){
            throw new BusinessException(ErrorCode.MATCH_ERROR,"未匹配到用户");
        }
        // 根据ID查询用户完整信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userListVo);
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper).stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        Set<Long> matchedUsers = redisMatchHistoryService.getMatchedUsers(loginUser.getId());
        // 按顺序获取最终用户列表
        List<User> finalUserList = new ArrayList<>();
        if(Long.valueOf(matchedUsers.size()) ==Long.valueOf(userIdUserListMap.size()) ){
            redisMatchHistoryService.clearMatchedUsers(loginUser.getId());
            matchedUsers = redisMatchHistoryService.getMatchedUsers(loginUser.getId());
        }
        for (Long userId : userListVo) {
            //是否在redis里有记录
//            如果有记录，不再记录，换下一个直到轮完为止
            Integer userId1= Integer.valueOf(String.valueOf(userIdUserListMap.get(userId).get(0).getId()) ) ;
            if(matchedUsers.contains( userId1)){
                continue;
            }
            redisMatchHistoryService.addMatchedUser(loginUser.getId(), userIdUserListMap.get(userId).get(0).getId());
            finalUserList.add(userIdUserListMap.get(userId).get(0));
            break;
        }



        return finalUserList;
    }

    @Override
    public User checkLogin(WxLoginDto wxLoginDto) throws IOException {
        String openId = getOpenId(wxLoginDto.getCode());
        //openid为空
        if(openId==null){
            throw new BusinessException(ErrorCode.LOGIN_FAILD);
        }
        //判断新用户
        //新用户 注册
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenId,openId);
        User user = userMapper.selectOne(wrapper);
        if(user==null){

           user= User.builder()
                    .username("微信用户")
                    .avatarUrl("https://pter-img.oss-cn-hangzhou.aliyuncs.com/2024/01/11/d8a0e624f6334b46bb76daf3aa116a53peter.jpg")
                    .userPassword("123123123")
                    .userStatus(0)
                    .isDelete(0)
                    .userRole(0)
                   .openId(openId)
                   .tags("[]")
                    .createTime(new Date()).build();

            userMapper.insert(user);
        }
        return user;
    }

    private String getOpenId(String code){
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", AppId);
        map.put("secret", AppSecret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //发送请求拿到openid
        String json = HttpClientUtils.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;

    }
    /**
     * sql查询版（sql语句一把梭）
     * @param tagNameList
     * @return
     */
//    @Deprecated
    private List<User> getUserByTagNameListBySql(List<String> tagNameList) {
        //判空
        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        for (String tagName:tagNameList) {
            queryWrapper=queryWrapper.like("tags",tagName);
        }
        List<User> userList=userMapper.selectList(queryWrapper);
        userList =userList.stream().map(item->{
            return getSafetyUser(item);
        }).collect(Collectors.toList());
        return userList;
    }

}

